package com.biodiv.community.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author tianquan
 */
@Component
public class JwtUtils {


    @Value("${jwt.secret}")
    private String varSecret;

    @Value("${jwt.expiration}")
    private long varExpiration;

    @Value("${jwt.refreshThreshold}")
    private long varRefreshThreshold;


    // 秘钥，用于签名（注意：应存放在安全的地方）
    private static String secret;

    // 单位：秒
    private static long expiration;

    // 刷新阈值（秒）
    private static long refreshThreshold;


    @PostConstruct
    public void init() {
        secret = varSecret;
        expiration = varExpiration;
        refreshThreshold = varRefreshThreshold;
    }

    /**
     * 生成 Token
     *
     * @param userId 用户 ID
     * @return 生成的 Token
     */
    public static String generateToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);

        return Jwts.builder()
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(getSecretKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    // 解析用户ID
    public static Long getUserIdFromToken(String token) {
        Claims claims = Jwts.parserBuilder()
                .setSigningKey(getSecretKey())
                .build()
                .parseClaimsJws(token)
                .getBody();

        return claims.get("userId", Long.class);
    }

    // 验证Token有效性
    public static boolean validateToken(String token) {
        try {
            Jwts.parserBuilder().setSigningKey(getSecretKey()).build().parseClaimsJws(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    // 检查是否需要刷新Token
    public static boolean shouldRefreshToken(String token) {
        try {
            Date expiration = Jwts.parserBuilder()
                    .setSigningKey(getSecretKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration();

            return (expiration.getTime() - System.currentTimeMillis()) < (refreshThreshold * 1000);
        } catch (Exception e) {
            return false;
        }
    }


    private static SecretKey getSecretKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }


}

